import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    Token: getToken(),
    Name: '',
    No: '',
    Next: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.Token = token
  },
  SET_NAME: (state, name) => {
    state.Name = name
  },
  SET_NO: (state, no) => {
    state.No = no
  },
  SET_NEXT: (state, next) => {
    state.Next = next
  }
}

const actions = {
  // user login
  login ({ commit }, userInfo) {
    const { Username, Password } = userInfo
    return new Promise((resolve, reject) => {
      login({ Username: Username, Password: Password }).then(response => {
        const { Data } = response
        if (!Data) {
          return reject(response.Code)
        }
        commit('SET_TOKEN', Data.Token)
        commit('SET_NAME', Data.Name)
        commit('SET_NO', Data.No)
        setToken(Data.Token)
        if(Data.No.length > 8) {
          commit('SET_NEXT', '/student')
        } else {
          commit('SET_NEXT', '/admin')
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        const { Code } = data
        if (Code === 400) {
          removeToken()
          commit('RESET_STATE')
          // eslint-disable-next-line no-undef,prefer-promise-reject-errors
          return reject('会话失效,请重新登录')
        } else {
          resolve()
        }
      }).catch(error => {
        // eslint-disable-next-line no-undef
        reject(error)
      })
      resolve()
    })
  },

  // user logout
  logout ({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
